// 行程相关的 HTTP 操作
import http from '@/https/http.js'

// 获取行程列表
export const getItineraryList = async (params = {}) => {
	try {
		// 参数处理，确保必填字段存在默认值
		const requestParams = {
			OpenId: null,
			ItineraryName: null,
			Status: null,
			PageNum: 1, // 默认第一页
			PageSize: 10, // 默认每页10条
			TotalNum: 0,
			...params
		}

		const res = await http.post('Mini/Itinerary/GetList', requestParams)
		return res
	} catch (error) {
		console.error('获取行程列表失败:', error)
		throw error
	}
}

// 创建行程
export const createItinerary = async (itineraryData) => {
	try {
		// 设置默认值
		const requestData = {
			itineraryId: 0,
			status: 0, // 默认正常状态
			...itineraryData
		}

		const res = await http.post('Mini/Itinerary/Create', requestData)
		return res
	} catch (error) {
		console.error('创建行程失败:', error)
		throw error
	}
}

// 更新行程信息
export const updateItinerary = async (itineraryData) => {
	try {
		// 设置默认值，并确保OpenId正确设置
		const requestData = {
			status: 0, // 默认正常状态
			OpenId: uni.getStorageSync('openId') || 0,
			...itineraryData
		}

		const res = await http.post('Mini/Itinerary/Update', requestData)
		return res
	} catch (error) {
		console.error('更新行程信息失败:', error)
		// 添加详细错误信息显示
		throw new Error('更新失败: ' + (error.message || '未知错误'))
	}
}

// 根据ID获取行程详情
export const getItineraryById = async (itineraryId) => {
	try {
		if (!itineraryId) {
			throw new Error('获取行程详情失败：行程ID不能为空')
		}
		
		// 使用新的Mini/Itinerary/GetById接口，从本地存储获取OpenId
		const requestParams = {
			Id: itineraryId,
			OpenId: uni.getStorageSync('openId') || 0
		}

		const res = await http.post('Mini/Itinerary/GetById', requestParams)
		return res
	} catch (error) {
		console.error('获取行程详情失败:', error)
		throw error
	}
}
// 获取行程下拉列表 
export const GetSelectList = async () => {
	try {
  
		const requestParams = {
			OpenId: uni.getStorageSync('openId') || 0
		}

		const res = await http.post('Mini/Itinerary/GetSelectList', requestParams)
		// 确保返回的是标准的{Value, Label}格式数组
		if (Array.isArray(res)) {
			return res;
		}
		return []
	} catch (error) {
		console.error('获取行程下拉列表:', error)
		throw error
	}
}

// 删除行程
export const deleteItineraryById = async (itineraryId) => {
	try {
		if (!itineraryId) {
			throw new Error('删除行程失败：行程ID不能为空')
		}
		// 参数处理，确保必填字段存在默认值
		const requestParams = {
			OpenId: null,
			Id: itineraryId
		}

		const res = await http.post('Mini/Itinerary/DeleteById', requestParams)
		return res
	} catch (error) {
		console.error('删除行程失败:', error)
		throw error
	}
}